<template>
  <div class="app-main-container">
    <div class="app-main-title">
      {{ translate("taskPeo") }}
      <div class="goback" @click="goBack">
        <i class="el-icon-refresh-left" /> {{ translate("backPage") }}
      </div>
    </div>
    <div class="doumee-filter">
      <el-form inline label-suffix="：">
        <el-form-item :label="translate('taskPeoInfo')">
          <el-input
            v-model="filters.memberName"
            :placeholder="translate('taskPeoPlace')"
          />
        </el-form-item>
        <el-form-item>
          <el-button v-preventReClick type="primary" @click="handleQuery">{{
            translate("cz")
          }}</el-button>
          <el-button v-preventReClick @click="clear">{{
            translate("clear")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="doumee_table_header">
      <el-button
        v-if="meta.indexOf('addShareUsers') > -1"
        v-preventReClick
        type="primary"
        @click="handleIncreaset"
      >{{ translate("tianjia") }}</el-button>
      <el-button
        v-if="meta.indexOf('exportShareUsers') > -1"
        :loading="exportLoading"
        @click="handleExport"
      >{{ translate("export") }}</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        prop="shareName"
        :label="translate('taskName')"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        prop="memberName"
        :label="translate('taskPeo')"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        prop="phone"
        :label="translate('phone')"
        min-width="120"
      />
      <el-table-column
        align="center"
        prop="lastMoney"
        :label="translate('zjybjyjl')"
        min-width="140"
      />
      <el-table-column
        align="center"
        prop="orderNum"
        :label="translate('ljfybs')"
        min-width="120"
      />
      <el-table-column
        align="center"
        prop="orderMoney"
        :label="translate('ljfydde')"
        min-width="120"
      />
      <el-table-column
        align="center"
        prop="moneyAward"
        :label="translate('ljfyje')"
        min-width="120"
      />
      <el-table-column
        align="center"
        prop="createTime"
        :label="translate('joinTime')"
        min-width="160"
      />
      <el-table-column
        align="center"
        prop="status"
        :label="translate('userStatus')"
        min-width="120"
      >
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.status"
            @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" :label="translate('handle')" width="120">
        <template v-slot="scope">
          <el-button
            v-if="meta.indexOf('removeShareUser') > -1"
            type="text"
            class="danger"
            @click="handleDel(scope.row)"
          >{{ translate("del") }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="totalCount"
      :page="pagination.page"
      @current-change="currentPageChange"
      @SizeChange="pageSizeChange"
    />

    <el-dialog
      :close-on-click-modal="modalDialog"
      :lose-on-press-escape="modalDialog"
      :title="translate('glfyyh')"
      :visible.sync="isopenModal"
      width="800px"
    >
      <div>
        <div>
          <el-form
            ref="form"
            label-suffix="："
            :model="modalForm"
            label-width="auto"
          >
            <el-form-item
              :label="translate('glyg')"
              prop="memberIds"
              :rules="[
                {
                  type: 'array',
                  required: true,
                  message: translate('glygbnwk'),
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                v-model="modalForm.memberIds"
                filterable
                remote
                collapse-tags
                :remote-method="remoteMethod"
                multiple
                :loading="loading"
                class="w400"
                :placeholder="translate('qxzzcss')"
              >
                <el-option
                  v-for="item in memberlist"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isopenModal = false">{{
          translate("cancel")
        }}</el-button>
        <el-button :loading="subLoading" type="primary" @click="IncreasetSub">{{
          translate("qd")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { shareUsers, addShareUsers, delShareUsers, memberList, changeShareUserStatus, ShareUserExport } from '@/api'
import dayjs from 'dayjs'

import Paginations from '@/components/paginations'
export default {
  name: 'SharePeople',
  components: {
    Paginations
  },
  data() {
    return {
      meta: [],
      modalDialog: this.$store.state.app.dialog,
      id: '',
      shareUsers: '',
      filters: {},
      modalForm: {
        memberIds: []
      },
      subLoading: false,
      loading: false,
      pagination: {
        page: 1,
        rows: 10
      },
      isopenModal: false,

      list: [],
      memberlist: [],
      totalCount: 0,
      exportLoading: false,
      listLoading: false
    }
  },
  activated() {
    this.meta = this.$route.meta.buttons || []
    this.id = this.$route.query.id || ''
    this.shareUsers = this.$route.query.shareUsers || ''
    this.getList()
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.id = this.$route.query.id || ''
    this.shareUsers = this.$route.query.shareUsers || ''
    this.getList()
  },
  methods: {
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          const param = {
            key: query
          }
          const pagination = {
            page: 1,
            rows: 30,
            firstQueryTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
          }
          memberList({ param, pagination }).then(res => {
            this.memberlist = res.recordList
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    getMemberlist() {
      // const param = { type: '1' }
      const param = {}
      const pagination = {
        page: 1,
        rows: 1000,
        firstQueryTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
      }
      memberList({ param, pagination }).then(res => {
        this.memberlist = res.recordList
      })
    },
    handleQuery() {
      this.page = 1
      this.getList()
    },
    handleIncreaset() {
      if (this.shareUsers === '1') {
        return this.$message.warning(this.translate('qbkfmswftj'))
      }
      this.modalForm.memberIds = []
      console.log(this.modalForm.memberIds)
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      this.modalForm = {}
      this.getMemberlist()
      this.isopenModal = true
    },
    handleExport() {
      const param = { ...this.filters }
      param.shareId = this.id
      this.exportLoading = true
      ShareUserExport({ param }).then(res => {
        this.exportLoading = false
        if (res.errorCode === '000000') {
          window.open(res.record.showUrl, '_blank')
        }
      }, () => {
        this.exportLoading = false
      })
    },
    getList() {
      const param = { ...this.filters }
      const pagination = this.pagination
      param.shareId = this.id
      this.listLoading = true
      shareUsers({ param, pagination }).then(res => {
        this.listLoading = false
        this.list = res.recordList || []
        this.list.forEach(item => {
          item.status = item.status === '0'
        })
        this.totalCount = res.totalCount
      })
    },
    IncreasetSub() {
      const { memberIds } = this.modalForm
      // if (memberIds.length === 0) {
      //   return this.$message.warning('请先选择关联员工')
      // }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const param = {
            memberIds,
            shareId: this.id
          }
          this.subLoading = true
          addShareUsers({ param }).then(res => {
            this.subLoading = false
            if (res.errorCode !== '000000') return
            this.handleQuery()
            this.$message.success(this.translate('tianjiaScs'))
            this.isopenModal = false
          }, () => {
            this.subLoading = false
          })
        }
      })
    },
    changeStatus(item) {
      if (this.meta.indexOf('changeShareUserStatus') === -1) {
        return this.handleQuery()
      }
      const param = {
        id: item.id,
        status: item.status ? '0' : '1'
      }
      changeShareUserStatus({ param }).then(res => {
        this.handleQuery()
        if (res.errorCode !== '000000') return
        this.$message.success(this.translate('xgryztcs'))
      }, () => {
        this.handleQuery()
      })
    },
    handleDel(item) {
      if (this.shareUsers === '1') {
        return this.$message.warning(this.translate('qbkfmswftj'))
      }
      this.$confirm(this.translate('czzjscgrwry'), this.translate('ts'), {
        confirmButtonText: this.translate('qd'),
        cancelButtonText: this.translate('cancel'),
        type: 'warning'
      }).then(() => {
        delShareUsers({ param: { id: item.id }}).then(res => {
          if (res.errorCode !== '000000') return
          this.$message.success(this.translate('delScs'))
          this.handleQuery()
        })
      })
    },
    currentPageChange(val) {
      this.pagination.page = val
      this.getList()
    },
    pageSizeChange(val) {
      this.pagination.rows = val
      this.getList()
    },
    goBack() {
      this.$router.replace('/application/shareModule?activeTab=1')
    },
    clear() {
      this.filters = {}
      this.handleQuery()
    }
  }
}
</script>

<style>
</style>
